package com.study.jyg.rxjava2study.activity.mywidget;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import androidx.appcompat.widget.Toolbar;
import android.widget.Button;
import android.widget.TextView;

import com.study.jyg.rxjava2study.R;
import com.study.jyg.rxjava2study.activity.wifidevicesearch.pingwifiip.NetToolTask;
import com.study.jyg.rxjava2study.base.BasicActivity;
import com.study.jyg.rxjava2study.widget.ScanView;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;

public class ScanViewActivity extends BasicActivity implements NetToolTask.NetToolTaskListener {

    private ScanView scanView;
    private Button btnStart;
    private Button btnStop;
    private TextView tvIp;
    private Toolbar toolbar;

    private List<String> list;

    @Override
    protected int getLayout() {
        return R.layout.activity_scan_view;
    }

    @Override
    protected void initView() {
        list = new ArrayList<>();
        toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(v -> finish());
        scanView = findViewById(R.id.scanView);
        btnStart = findViewById(R.id.btnStart);
        btnStop = findViewById(R.id.btnStop);
        tvIp = findViewById(R.id.tvIp);
        btnStart.setOnClickListener(v -> {
            scanView.start();
            for (int i = 0; i < 256; i++) {
                NetToolTask task = new NetToolTask();
                task.setNetToolTaskListener(this);
                task.executeOnExecutor(Executors.newCachedThreadPool(), i);
            }
        });
        btnStop.setOnClickListener(v -> {
            scanView.stop();
        });
    }

    @Override
    public void linkSuccess(String ip) {
        tvIp.setText( ip);
    }

    @Override
    public void sendMsgSuccess(String result) {
        list.add(result);
        if (!mHandler.hasMessages(100)){
            mHandler.sendEmptyMessage(100);
        }
    }

    @SuppressLint("HandlerLeak")
    private final Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 100:
                    if (list.size()>0){
                        String ip = list.get(0);
                        tvIp.setText(ip);
                        list.remove(0);
                        if (list.size()>0){
                            mHandler.sendEmptyMessageDelayed(100, 1000);
                        }
                    }
                    break;

            }
        }
    };

}